package com.immunology.servlets;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.immunology.database.ConnectionManager;
import com.immunology.model.MappingPages;

public class ComplaintTypeServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	public ComplaintTypeServlet() {
		super();
	}

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		getServletContext().getRequestDispatcher(MappingPages.COMPLAINT_TYPE)
				.forward(request, response);
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String complaintName = request.getParameter("complaintName");
		String complaintMultyplier = request
				.getParameter("complaintMultyplier");

		ConnectionManager connectionManager = new ConnectionManager();
		Connection connection = connectionManager.getConnection();

		PreparedStatement preparedStatement = null;
		try {
			String sql = "INSERT INTO complaint_type VALUES(?,?,?)";
			preparedStatement = connection.prepareStatement(sql);
			preparedStatement.setInt(1, getNextId(connection));
			preparedStatement.setString(2, complaintName);
			preparedStatement.setDouble(3,
					Double.parseDouble(complaintMultyplier));
			preparedStatement.executeUpdate();

		} catch (Exception e) {
			System.out.println("Create statement error");
		}

		if (connectionManager != null)
			connectionManager.closeConnection(connection);
		response.sendRedirect("complaintType");
	}

	private int getNextId(Connection connection) throws SQLException {
		int id = 0;
		String sql = "SELECT * FROM complaint_type";
		Statement statement = connection.createStatement();
		ResultSet resultSet = statement.executeQuery(sql);
		while (resultSet.next()) {
			id = resultSet.getInt(1);
		}
		statement.close();
		resultSet.close();
		return ++id;
	}
}
